#  main.py
#  
#  Copyright 2011 Alexey Zotov <alexey.zotov@gmail.com>
#  
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#  
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.

# -*- coding: utf-8 -*-

import dbus
import dbus.service
from dbus.mainloop.qt import DBusQtMainLoop

from PyQt4 import QtCore
from PyQt4 import QtGui

from PyKDE4 import plasmascript
from PyKDE4.plasma import Plasma

BUS_NAME = 'org.new_wallpaper.Plasmoid'
OBJ_PATH = '/org/new_wallpaper/Plasmoid'

class KSetWallpaper(plasmascript.Applet):
    def __init__(self, parent, args=None):
        super(KSetWallpaper, self).__init__(parent)

    def init(self):
        self.setAspectRatioMode(Plasma.Square)

        self.icon = QtGui.QIcon.fromTheme('video-display')
        self.icon_widget = Plasma.IconWidget()
        self.icon_widget.setIcon(self.icon)
        layout = QtGui.QGraphicsLinearLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        layout.addItem(self.icon_widget)
        self.setLayout(layout)

        corona = self.containment().corona()
        screen = self.containment().screen()
        if screen < 0:
            screen = 0
        self.screen = corona.containmentForScreen(screen)

        self.bus = dbus.SessionBus()
        self.name = dbus.service.BusName(BUS_NAME)
        self.dbus_object = Plasmoid(self.bus, OBJ_PATH + '/%s' % screen, self)

    def set_wallpaper(self, wallpaper):
        if not self.screen.wallpaper():
            return

        QtCore.QMetaObject.invokeMethod(
            self.screen.wallpaper(),
            'setWallpaper',
            QtCore.Q_ARG(QtCore.QString, wallpaper)
        )

class Plasmoid(dbus.service.Object):
    def __init__(self, bus, path, applet):
        super(Plasmoid, self).__init__(bus, path)

        self.applet = applet

    @dbus.service.method(BUS_NAME, in_signature='s', out_signature='')
    def SetWallpaper(self, wallpaper):
        self.applet.set_wallpaper(wallpaper)

def CreateApplet(parent):
    DBusQtMainLoop(set_as_default=True)
    return KSetWallpaper(parent)
